﻿using AutoMapper;
using HamcoWcs.Contract.ContractCommon;
using HamcoWcs.DAL;
using HamcoWcs.Entitys.Logss;
using Quartz;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace HamcoWcs.Workers.LoggerWorkers
{
    [DisallowConcurrentExecution]
    public class LoggerWorker_Communicate : WorkerBase
    {
        public LoggerWorker_Communicate(WcsDbContext wcsDbContext, IMapper mapper, ILoggerService logger) : base(wcsDbContext, mapper, logger)
        {
        }

        public override Task Execute(IJobExecutionContext context)
        {
            DoBackup();
            DoDelete();
            return Task.CompletedTask;
        }

        private void DoDelete()
        {
            try
            {
                var tDate = DateTime.Now.Date.AddDays(-90);
                if (!_wcsDbContext.Set<CommunicationLogBak>().Any(x => x.CreatedTime < tDate)) return;

                var logbaks = _wcsDbContext.Set<CommunicationLogBak>().Where(x => x.CreatedTime < tDate).ToList();
                if (logbaks.Count == 0) return;
                _wcsDbContext.Set<CommunicationLogBak>().RemoveRange(logbaks);
                _wcsDbContext.SaveChanges();
            }
            catch (Exception ex)
            {
                _logger.AddSystemErrorLog($"LoggerWorker->Communicate->DoDelete:{ex.Message}");
            }
        }

        private void DoBackup()
        {
            try
            {
                var tDate = DateTime.Now.Date.AddDays(-7);
                if (!_wcsDbContext.Set<CommunicationLogBak>().Any(x => x.CreatedTime < tDate)) return;

                var logs = _wcsDbContext.Set<CommunicationLog>().Where(x => x.CreatedTime < tDate).Take(1000).ToList();
                if (logs.Count == 0) return;
                var logbaks = _mapper.Map<List<CommunicationLogBak>>(logs);
                _wcsDbContext.Set<CommunicationLogBak>().AddRange(logbaks);
                _wcsDbContext.Set<CommunicationLog>().RemoveRange(logs);
                _wcsDbContext.SaveChanges();

            }
            catch (Exception ex)
            {
                _logger.AddSystemErrorLog($"LoggerWorker->Communicate->DoBackup:{ex.Message}");
            }
        }
    }
}
